package wzj.mybatisplusdemo.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import wzj.mybatisplusdemo.po.User;
import wzj.mybatisplusdemo.service.UserServie;
import wzj.mybatisplusdemo.web.dto.RespEntity;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

@CrossOrigin
@RestController
public class UserController {
    @Autowired
    private UserServie userServie;
    @Value("${my.reg_score}")
    private int score;
    @PostMapping("/reg")
    public RespEntity register(@RequestBody User user) {
        user.setScore(score);
        userServie.save(user);
        return new RespEntity("2000","注册成功",null);
    }

    @PostMapping("/login")
    public RespEntity login(String loginName, String loginPwd) {
        QueryWrapper<User> qw = new QueryWrapper<>();
//        qw.eq("u_loginname", loginName);
//        qw.eq("u_loginpwd", loginPwd);
        qw.lambda().eq(User::getLoginName, loginName).eq(User::getLoginPwd, loginPwd);
        User user = userServie.getOne(qw);
        if (user == null) {
            return new RespEntity("4000","用户名或密码错误",null);
        }

        JwtBuilder builder = Jwts.builder();
        builder.setId(UUID.randomUUID().toString());
        builder.setIssuedAt(new java.util.Date());
        builder.setExpiration(new Date(System.currentTimeMillis()+ 1000*60*60*24));
        builder.signWith(SignatureAlgorithm.HS256, "123456");
        builder.setClaims(
                Map.of("id",user.getId()
                        ,"nickName",user.getNickName()
                        ,"loginPwd",user.getLoginPwd()
                        ,"loginName",user.getLoginName()
                        ,"email",user.getEmail()
                        ,"score",user.getScore()
                ));
//        builder.setSubject(user.getId()+"");
        String jwttoken = builder.compact();
        System.out.println(jwttoken);
        user.setLoginPwd(null);
        return new RespEntity("2000","登陆成功",Map.of("token",jwttoken, "user",user)    );
    }

//    @PostMapping("/reg")
//    public String register(String loginName,String loginPwd,String nickName,String email) {
//        User user = new User();
//        user.setLoginName(loginName);
//        user.setLoginPwd(loginPwd);
//        user.setNickName(nickName);
//        user.setEmail(email);
//        user.setScore(20);
//        userServie.save(user);
//        return "{\"code\":200,\"msg\":\"注册成功\",\"data\":null}";
//    }
}
